package com.example.studentalarm.service;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;

import com.example.studentalarm.R;
import com.example.studentalarm.bean.TimetableBean;
import com.example.studentalarm.constant.ApiConstant;
import com.example.studentalarm.database.DbManager;
import com.example.studentalarm.utils.LogUtil;
import com.example.studentalarm.utils.TimeUtils;

import java.util.Calendar;
import java.util.List;

/***
 * 闹钟服务类，此处于单独一个主线程与Ui线程不是同一个主线程
 */
public class AlarmService extends Service {
    private AlarmManager am;
    private PendingIntent pi;

    public AlarmService() {

    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        releaseWakeLock();
        LogUtil.e("onUnbind 。。。。");
        return super.onUnbind(intent);
    }


    @Override
    public void onCreate() {
        super.onCreate();
        LogUtil.e("alarmService on create。。。。。");
        if (Build.VERSION.SDK_INT >= 26) {
            silentForegroundNotification();
        }
        acquireWakeLock();
    }

    @TargetApi(26)
    private void silentForegroundNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String CHANNEL_ID = "my_app";
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("")
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setAutoCancel(true)
                    .setShowWhen(true)
                    .setSmallIcon(R.mipmap.app_logo);
            startForeground(1, builder.build());
            stopForeground(true);
        }
    }


    PowerManager.WakeLock wakeLock = null;    //获取电源锁，保持该服务在屏幕熄灭时仍然获取CPU时，保持运行

    @SuppressLint("InvalidWakeLockTag")
    private void acquireWakeLock() {
        if (null == wakeLock) {
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "AlarmService");
            if (null != wakeLock) {
                wakeLock.acquire();
            }
        }
    }


    //释放设备电源锁
    private void releaseWakeLock() {
        if (null != wakeLock) {
            wakeLock.release();
            wakeLock = null;
        }
    }

    @Override
    public int onStartCommand(Intent pIntent, int pFlags, int pStartId) {
        LogUtil.e("alarmService onStartCommand。。。。。");
        getAlarmTime();
        return START_REDELIVER_INTENT;
    }

    public void getAlarmTime() {
        DbManager.getInstance().onInit(this);
        List<TimetableBean> beanList = DbManager.getInstance().queryTimetableList();
        if (beanList != null && beanList.size() > 0) {
            for (TimetableBean bean : beanList) {
                long currentTime = System.currentTimeMillis();
                Calendar mCalendar = Calendar.getInstance();
                mCalendar.setTimeInMillis(currentTime);
                int minute = mCalendar.get(Calendar.MINUTE);//当前的分钟
                int mHour = mCalendar.get(Calendar.HOUR_OF_DAY);//当前的小时
                long beforeTime = bean.getMinute() * 60 * 1000;//提前的时间
                long alarmTime = bean.getTime().getTime();//闹钟的时间
                Long time = alarmTime - beforeTime;
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(time);
                int alarmMinute = calendar.get(Calendar.MINUTE);//闹钟的分钟
                int alarmHour = calendar.get(Calendar.HOUR_OF_DAY);//闹钟的小时
                LogUtil.e("告警通知状态：" + bean.getAlarmState() + " 当前时间：" + mHour + ":" + minute + "  告警时间：" + alarmHour + ":" + alarmMinute);
                boolean isExecute = true;
                if (beforeTime == 0) {
                    isExecute = (alarmHour >= mHour && alarmMinute >= minute);
                } else if (beforeTime > 0) {
                    //如果是提前多少分钟的话，
                    isExecute = true;
                }
                if (bean.getAlarmState() == ApiConstant.AlarmState.UNSEND&&isExecute) {
                    LogUtil.e("提前多少分钟：" + bean.getMinute());
                    Intent startNotification = new Intent(this, AlarmReceiver.class);
                    startNotification.setAction(AlarmReceiver.ACTION_ALARM_ALERT);
                    startNotification.putExtra("alarmId", bean.getId());
                    startNotification.putExtra("title", bean.getName());
                    startNotification.putExtra("content", bean.getAddress());
                    am = (AlarmManager) getSystemService(ALARM_SERVICE);   //这里是系统闹钟的对象
                    pi = PendingIntent.getBroadcast(getApplicationContext(), bean.getId(), startNotification, PendingIntent.FLAG_UPDATE_CURRENT);     //设置事件
                    LogUtil.e("主键id：" + bean.getId() + "闹钟时间：" + TimeUtils.getDate("yyyy-MM-dd HH:mm:ss", alarmTime) +
                            "\n 提前的时间：" + TimeUtils.getDate("yyyy-MM-dd HH:mm:ss", time));
                    if (time != null) {
                        am.setRepeating(AlarmManager.RTC_WAKEUP, time, 3 * 1000, pi);
                    } else {
                        //当提醒时间为空的时候，关闭服务，下次添加提醒时再开启
                        stopService(new Intent(this, AlarmService.class));
                    }
                } else {
                    //可以做取消闹钟操作，且提需要判断当前状态是否打开状态
                    // cancelAlarm(this,bean.getId());
                }

            }

        }
    }

    /***
     * 取消闹钟
     * @param mContext
     * @param alarmId
     */
    public void cancelAlarm(Context mContext, Integer alarmId) {
        Intent intent = new Intent(mContext, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(mContext, alarmId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pi);
    }

    @Override
    public void onTaskRemoved(Intent pIntent) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DbManager.getInstance().closeDB();
        LogUtil.e("alarmService onDestroy。。。。。");
    }
}
